/**
 * Project Looking Glass
 *
 * $RCSfile: ButtonComponent.java,v $
 *
 * Copyright (c) 2004-2007, Sun Microsystems, Inc., All Rights Reserved
 *
 * Redistributions in source code form must reproduce the above
 * copyright and this condition.
 *
 * The contents of this file are subject to the GNU General Public
 * License, Version 2 (the "License"); you may not use this file
 * except in compliance with the License. A copy of the License is
 * available at http://www.opensource.org/licenses/gpl-license.php.
 *
 * $Revision: 1.3 $
 * $Date: 2007/05/04 23:11:40 $
 * $State: Exp $
 */
package lionel.input;

import javax.swing.event.EventListenerList;
import net.java.games.input.Component;

/**
 * A Button or a Key component of a JInput controller
 *
 * @author Krishna Gadepalli
 */
public class ButtonComponent extends JInputComponent {

    public ButtonComponent(JInputDevice device, Component component) {
	super(device, component);
    }

    public String toString() {
	return component.getName() + "[value=" + currentValue + "]";
    }

    /**
     * Figure out the button/key events generated after the last poll (by comparing last polled
     * state to current state) and send the appropriate events to the registered
     * listeners.
     */
    public void sendEvent(EventListenerList listenerList) {
	boolean pressed  = (previousValue == 0) && (currentValue != 0);
	boolean released = (previousValue != 0) && (currentValue == 0);

	if (!pressed && !released)
	    return;

	// Guaranteed to return a non-null array
	Object[] listeners = listenerList.getListenerList();
	ButtonEvent e = null;
	// Process the listeners last to first, notifying
	// those that are interested in this event
	for (int i = listeners.length-2; i>=0; i-=2) {
	    if (listeners[i]==ButtonEventListener.class) {
		// Lazily create the event:
		if (e == null)
		    e = new ButtonEvent(device, this, currentValue);

		if (pressed)
		    ((ButtonEventListener)listeners[i+1]).buttonPressed(e);
		else
		    ((ButtonEventListener)listeners[i+1]).buttonReleased(e);
	    }          
	}
    }
}
